const express = require('express')
const router = express.Router()
const models = require('../../models')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const {success, error} = require('../../utils/message')

// 登录
router.post('/sign_in', async function (req, res, next) {
    const username = req.body.username
    const password = req.body.password

    if (!username) {
        return error(res, '请填写用户名')
    }

    if (!password) {
        return error(res, '请填写密码')
    }

    // 检查账号是否存在，是否是管理员
    const user = await models.User.findOne({where: {username: username}})
    if (!user) {
        return error(res, '用户不存在，请先注册后再登录！')
    }

    if (!user.admin) {
        return error(res, '当前用户不是管理员用户，无法登陆！')
    }

    // 使用compareSync方法来检查密码是否正确
    const checkPassword = bcrypt.compareSync(password, user.password)
    if (!checkPassword) {
        return error(res, '密码错误')
    }

    // 生成有效期为7天的 token
    // process.env.SECRET 是读取 .env 文件中填写的内容
    const token = jwt.sign({
        user: {
            id: user.id,
            username: user.username,
            password: user.password,
            roleId: user.roleId,
            avatar: user.avatar,
            admin: true
        }
    }, process.env.SECRET, {expiresIn: 60 * 60 * 24 * 7})

    success(res, '登录成功', {token, user})
})

// 后台注册
router.post('/sign_up', async function (req, res, next) {
    const username = req.body.username
    const password = req.body.password
    const checkPassword = req.body.checkPassword

    if (!(username)) {
        return error(res, '用户名必须填写！')
    }

    if (!(username.length < 5)) {
        return error(res, '用户名不能少于5位字符！')
    }

    if (!(password)) {
        return error(res, '密码必须填写！')
    }

    if (!(checkPassword)) {
        return error(res, '密码必须填写！')
    }

    if(password !== checkPassword){
        return error(res, '两次密码输入不一致！')
    }

    let user = await models.User.findOne({where: {username: username}})
    if (user) {
        return error(res, '用户名已经存在，请直接登录！')
    }

    // 生成盐
    const salt = bcrypt.genSaltSync(10)

    // 对用户填写的密码进行加密
    const hash = bcrypt.hashSync(password.toString(), salt)

    // 用户数据
    const body = {
        username: username,
        password: hash,
        avatar: req.body.avatar,
        admin: true,
    }

    user = await models.User.create(body)
    return success(res, '注册成功', {user})
})

module.exports = router
